 <?php
    Connection::getConnect();
	$islistings =  $this->get('listing');
	$isdelete = $this->get('delete');
	$isadd = $this->get('add');
	$getlist = $this->get('getlist');
	$getlistid = $this->get('getlistid');
 	if (COUNT($_POST) && $isdelete)
	{
		$name = $this->get('name');
		$sql = "DELETE FROM item_category WHERE name='%s'";
        Connection::setQueryf($sql, $name);
		exit;
	}
 	if (COUNT($_POST) && $isadd)
	{
		$name = $this->get('name');
		$base = $this->get('base');
		
		
        $sql = "SELECT icid FROM item_category WHERE name='%s'";
        Connection::setQueryf($sql, $name);
		$isexist = Connection::fetch();
		if ($isexist['icid'] == 0)
		{
         	$sql = "INSERT INTO item_category(name, base_cat_id) VALUES('%s', %d)";
            Connection::setQueryf($sql, $name, $base);
    		if (!$base)
    			echo '<option value="' . mysql_insert_id() . '">' . $name . '</option>';
    			
    		$this->logger(INVENTORY, 'Category Added - name="' . $name . '".');
			echo 1;
		}
		else
		{
			echo "Already exist!";
		}
		exit;
	} 
	if ($islistings || $this->get('list') == 1)
	{
     	$sql = "SELECT *,(SELECT name FROM item_category i WHERE i.icid=ii.base_cat_id)as base FROM item_category ii ORDER BY base_cat_id";
        Connection::setQuery($sql);
    	$categories = Connection::fetchAll(MYSQL_ASSOC);
	}
	if ($getlist && $getlistid >=0)
	{
     	$sql = "SELECT * FROM item_category ii WHERE base_cat_id=%d";
        Connection::setQueryf($sql, $getlistid);
    	$categories2 = Connection::fetchAll(MYSQL_ASSOC);
		foreach ($categories2 as $category){
        	echo '<option value="' . $category['icid'] . '" base="' . $category['base_cat_id'] . '">' . $category['name'] . '</option>';
		}
		exit;
	}
 ?>
 
